import axios from 'axios';
// les接口
// 初始化实例
const request = axios.create({
  baseURL: '/les',
  // baseURL: 'http://192.168.50.145:8102/les',
  // baseURL: 'http://192.168.50.210:8888/les',
  timeout: 180000,
});
// 递归去除对象中的字符串前后空格
const trimObject = (obj: any) => {
  if (typeof obj !== 'object' || obj === null) return obj;
  // 判断是否为空对象
  if (Object.keys(obj).length === 0 && obj.constructor === Object) return obj;
  Object.keys(obj).forEach((key) => {
    const value = obj[key];
    if (typeof value === 'string') {
      // 如果值是字符串，去除前后空格
      obj[key] = value.trim();
    } else if (typeof value === 'object') {
      // 如果值是对象或数组，递归处理
      obj[key] = trimObject(value);
    }
  });
  return obj;
};
// 添加请求拦截器
request.interceptors.request.use(
  async (config) => {
    config.params = trimObject(config.params || {});
    config.data = trimObject(config.data || {});
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
request.interceptors.response.use(
  (response) => {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response;
  },
  (error) => {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    // console.log('响应拦截器报错:', error);
    return Promise.reject(error);
  }
);

export const $$get = async (url: string) => {
  const { data } = await request.get(url);
  return data;
};

export const $get = async (url: string, params: any) => {
  const { data } = await request.get(url, { params });
  return data;
};

export const $post = async (url: string, params: any) => {
  const { data } = await request.post(url, params);
  return data;
};
export const $$post = async (url: string) => {
  const { data } = await request.post(url);
  return data;
};

export const $put = async (url: string, params: any) => {
  const { data } = await request.put(url, params);
  return data;
};

export const $del = async (url: string, params: any) => {
  const { data } = await request.delete(url, { params });
  return data;
};
